<?php

/**
 * 主题管理
 */
namespace app\topics\model;

use app\system\model\SystemModel;

class TopicsDetailModel extends SystemModel {

    protected $infoModel = [
        'pri' => 'detail_id',
        'validate' => [
            'title' => [
                'len' => ['1, 250', '标题只能为1~250个字符', 'must', 'all'],
            ],
            'node_id' => [
                'empty' => ['', '请选择节点!', 'must', 'all'],
            ],
            'user_id' => [
                'empty' => ['', '用户ID不正确!', 'must', 'all'],
            ],
        ],
        'format' => [
            'node_id' => [
                'function' => ['intval', 'all'],
            ],
            'title' => [
                'function' => ['html_clear', 'all'],
            ],
            'tags' => [
                'function' => ['html_clear', 'all'],
            ],
            'description' => [
                'callback' => ['formatDesc', 'all'],
            ]

        ],
        'into' => 'title,node_id,user_id,tags,create_time,update_time,description,type',
        'out' => '',
    ];

    protected $nodeInfo = [];

    public function formatDesc($field, $data) {
        return  \dux\lib\Str::strMake($_POST['markdown'], 250);
    }

    public function changeHtml($data) {
        $parsedown = new \dux\vendor\Parsedown();
        $html = $parsedown->text($data);

        //转换昵称
        preg_match_all('/\@\@(.*)\@\@/U', $html, $result);

        if (empty($result)) {
            return $html;
        }
        foreach ($result[1] as $k => $v) {
            $info = target('topics/TopicsUser')->getWhereInfo([
                'username' => $v
            ]);
            if ($info) {
                $html = str_replace($result[0][$k], '<a href="' . url('topics/User/index', ['id' => $info['user_id']]) . '" target="_blank">@' . $v . '</a>', $html);
            }
        }
        return $html;
    }

    protected function base($where) {
        return $this->table('topics_detail(A)')
            ->join('topics_node(B)', ['B.node_id', 'A.node_id'])
            ->join('topics_user(C)', ['C.user_id', 'A.user_id'])
            ->field(['A.*', 'B.name(node_name)', 'C.username(show_name)', 'C.avatar'])
            ->where((array)$where);
    }

    public function loadList($where = array(), $limit = 0, $order = '') {
        $list = $this->base($where)
            ->limit($limit)
            ->order($order)
            ->select();

        $typeList = target('topics/Topics', 'service')->getTypeAll();
        foreach ($list as $key => $vo) {
            $list[$key]['avatar'] = $vo['avatar'] ? $vo['avatar'] : ROOT_URL . '/public/topics/images/logo.png';
            $list[$key]['url'] = url($typeList[$vo['type']]['info_url'], ['id' => $vo['detail_id']]);
        }
        return $list;
    }

    public function countList($where = array()) {
        return $this->base($where)->count();
    }

    public function getWhereInfo($where) {
        $info = $this->base($where)->find();
        if($info) {
            $info['avatar'] = $info['avatar'] ? $info['avatar'] : ROOT_URL . '/public/topics/images/logo.png';
        }
        return $info;
    }

    public function saveData($type = 'add', $data = []) {
        $data = $this->create($data);
        $time = time();
        $userInfo = target('topics/TopicsUser')->getInfo($data['user_id']);
        if (!$userInfo['status']) {
            $this->error = '您已被禁用，无法进行发布！';
            return false;
        }

        $lastInfo = $this->where(['user_id' => $data['user_id']])->order('create_time desc')->find();
        if ($lastInfo['create_time'] + 60 > time()) {
            $this->error = '一分钟内不能再次发布内容！';
            //return false;
        }

        $nodeInfo = target('topics/TopicsNode')->getInfo(intval($data['node_id']));
        if (empty($nodeInfo)) {
            $this->error = '节点选择错误！';
            return false;
        }

        $postRole = explode(',', $nodeInfo['post_role']);
        $postRole = array_filter($postRole);
        if (!empty($postRole) && !in_array($userInfo['role_id'], $postRole)) {
            $this->error = '您所在的用户组无法在本节点发表内容！';
            return false;
        }

        $data['ip'] = \dux\lib\Client::getUserIp();
        $data['update_time'] = $time;

        if(empty($data['tags'])) {
            $tagsList = target('topics/TopicsSearch')->getKeywords($_POST['title'], $_POST['markdown']);
            $data['tags'] = $tagsList ? implode(',', $tagsList) : '';
        }

        if ($type == 'add') {
            $data['create_time'] = $time;

            $titleInfo = $this->where(['title' => $data['title']])->count();
            if (!empty($titleInfo)) {
                $this->error = '您已发表过该内容！';
                return false;
            }
            $id = parent::saveData($type, $data);
            if (!$id) {
                return false;
            }
        } else {
            $data['edit_time'] = $time;
            if (parent::saveData($type, $data)) {
                return false;
            }
            $id = $data['detail_id'];
        }

        $status = target('topics/TopicsNode')->edit([
            'node_id' => $nodeInfo['node_id'],
            'count_post' => $nodeInfo['count_post'] + 1,
            'last_post_time' => $time,
        ]);
        if (!$status) {
            $this->error = target('topics/TopicsNode')->getError();
            return false;
        }

        $status = target('topics/TopicsTags')->addTags($data['tags'], $id);
        if (!$status) {
            $this->error = target('topics/TopicsTags')->getError();
            return false;
        }

        $status = target('topics/TopicsSearch')->indexData($id, $_POST['title'], $_POST['markdown'], $data['tags']);
        if (!$status) {
            $this->error = target('topics/TopicsSearch')->getError();
            return false;
        }

        /*
        if($nodeInfo['point_post_num']) {
            $status = target('member/Points', 'service')->account([
                'user_id' => $data['user_id'],
                'points' => $nodeInfo['point_post_num'],
                'type' => $nodeInfo['point_post_type'],
                'deduct' => true,
                'remark' => '发帖' . $nodeInfo['point_post_type'] ? '增加' : '扣除' . '积分'
            ]);
            if (!$status) {
                $this->error = target('member/Points', 'service')->getError();
                return false;
            }
        }
        */

        return $id;
    }


}